package com.zhao.reggie3.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @description: 全局异常处理器
 * @author: zhaoziliang
 * @time: 2022/8/15
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    /**
     * @description 添加重复异常处理
     * @param
     * @return
     **/
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionhandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            String[] s = ex.getMessage().split(" ");
            String s1 = s[2] + "已存在";
            return R.error(s1);
        }
        return R.error("未知错误");
    }
    /**
     * @description 异常处理方法
     * @param
     * @return
     **/
    @ExceptionHandler(ProductException.class)
    public R<String> exceptionhandler(ProductException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
